package com.game.shudu

import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

/**
 * 首页
 */
class MainActivity : AppCompatActivity() {
    private val TAG = "Sudoku"

    private var mExitTime = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
//继续游戏
        continue_button.setOnClickListener {
            startGame(Game.DIFFICULTY_CONTINUE)
        }
//新游戏
        new_game_button.setOnClickListener {
            AlertDialog.Builder(this)
                .setTitle(R.string.new_game_title)
                .setItems(
                    R.array.difficulty
                ) { _, which -> startGame(which) }.show()
        }
        //关于
        about_button.setOnClickListener {
            startActivity(Intent(this, About::class.java))
        }
        //退出
        exit_button.setOnClickListener {
            finish()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        super.onCreateOptionsMenu(menu)
        val inflater = menuInflater
        inflater.inflate(R.menu.menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.settings -> {
                startActivity(Intent(this, Prefs::class.java))
                return true
            }
        }
        return false
    }

    override fun onResume() {
        super.onResume()
        if (Prefs.getMusic(this)) Music.play(this, R.raw.do_you_remember)
    }

    override fun onPause() {
        super.onPause()
        if (Prefs.getMusic(this)) Music.stop(this)
    }

    private fun startGame(which: Int) {
        Log.d(TAG, "Clicked on $which")
        val intent = Intent(this, Game::class.java)
        intent.putExtra(Game.KEY_DIFFICULTY, which)
        startActivity(intent)
    }

    override fun onBackPressed() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            showToast("连按两下退出应用")
            mExitTime = System.currentTimeMillis()
        } else {
            super.onBackPressed()
        }
    }

    fun showToast(message: String, length: Int = Toast.LENGTH_SHORT) {
        Toast.makeText(this, message, length).show()
    }
}